package jdk8;

import java.util.Optional;

public class TestOptional {
    public static void main(String[] args) {
        String s1 = null;
        String s2 = "2 1 ";

        //System.out.println(TestOptional.trim(s2));
        //System.out.println(maxLengthStr("123", null));

        nullOptional();
    }

    public static String trim(String str) {
        // return Optional.ofNullable(str).map(s ->
        // s.trim()).orElseGet(()->{return "";});
        return Optional.ofNullable(str).map(s -> s.trim()).orElse("");
    }

    public static int maxLength(String s1, String s2) {
        return Math.max(Optional.ofNullable(s1).map(s -> s.length()).orElse(0), Optional.ofNullable(s2).map(s -> s.length()).orElse(0));
    }

    public static String maxLengthStr(String s1, String s2) {

/*        Optional.ofNullable(s1).orElseThrow(() -> {
            throw new RuntimeException("参数不能为null");
        });
        Optional.ofNullable(s2).orElseThrow(() -> {
            throw new RuntimeException("参数不能为null");
        });*/
        return s1.length() > s2.length() ? s1 : s2;

    }

    /**
     * 如果中间有一个是null 则都会返回orELse设置的结果  是不是很赞
     *
     * @return
     */
    public static String nullOptional() {
        String sky = Optional.ofNullable("sky").map(String::length).map(l -> null).map(s -> s + "_null").orElse("");
        System.out.println(sky);
        return sky;
    }
}
